'use strict';
/* Directives */
angular.module('aotaApp.directives', [])
    .directive('setTitle', function () {
        return {
            restrict: 'A',
            compile: function (tElem, attr) {
                tElem.html(attr.title);
            }
        };
    })
    .directive('setHeader', function () {
        return {
            restrict: 'A',
            compile: function (tElem, attr) {
                tElem.html(attr.header);
            }
        };
    })
    .directive('selectEmu', function () {
        return {
            link: function (scope, elem, attr) {
                // log(elem)
                elem.delegate('.dropdown-menu a', 'click', function () {
                    elem.find('.choosen-value').html($(this).html());
                });
            }
        };
    })

    .directive('showStar', function () {
        return {
            restrict: 'AE',
            replace: false,
            template: '<i class="fa fa-star-o"></i> <i class="fa fa-star-o"></i> <i class="fa fa-star-o"></i> <i class="fa fa-star-o"></i> <i class="fa fa-star-o"></i>',
            link: function (scope, elem, attr) {
                var starGrade = elem.attr('data-grade');
                var stars = elem.find('i');
                for (var s = 0; s < scope.app.appStartGrade; s++) {
                    $(stars[s]).attr('class', 'fa fa-star');
                }
            }
        };
    })
    .directive('markStar', function () {
        return {
            restrict: 'AE',
            replace: false,
            template: '<i class="fa fa-star-o star"></i><i class="fa fa-star-o star"></i><i class="fa fa-star-o star"></i><i class="fa fa-star-o star"></i><i class="fa fa-star-o star"></i>',
            link: function (scope, elem, attr) {
                var stars = elem.find('i');
                elem.on('mouseover', '.star', function () {
                    clearStar();
                    markStar(+$(this).attr('data-index'));
                });
                elem.on('mouseout', '.star', function () {
                    clearStar();
                });
                stars.each(function (i) {
                    $(this).attr('data-index', i + 1);
                    $(this).click(function () {
                        clearStar();
                        markStar(+$(this).attr('data-index'));
                        stars.removeClass('star');
                        scope.newApp.appStartGrade = +$(this).attr('data-index');
                    });
                });
                function clearStar() {
                    stars.each(function () {
                        $(this).attr('class', 'fa fa-star-o star');
                    })
                }

                function markStar(starGrade) {
                    for (var i = 0; i < starGrade; i++) {
                        $(stars[i]).attr('class', 'fa fa-star star');
                    }
                }
            }
        }
    })
    .directive('chkbox', function () {
        return {
            restrict: 'E',
            replace: true,
            template: '<div class="checkbox-group chk-item">' +
                '<div class="custom-checkbox bordered">' +
                '<i class="fa fa-check"></i>' +
                '</div>' +
                '</div>',
            link: function (scope, tElem, attr) {
                tElem.on('click', function () {
                    $(this).toggleClass('checked');
                });
            }
        };
    })
    .directive('chkboxAll', function () {
        return {
            restrict: 'E',
            replace: true,
            template: '<div class="checkbox-group chk-all"><div class="custom-checkbox bordered"><i class="fa fa-check"></i></div><label for=""></label></div>',
            compile: function (tElem, attr) {
                tElem.on('click', function () {
                    var jqThis = $(this);
                    jqThis.toggleClass('checked');

                    if (jqThis.hasClass('checked')) {
                        jqThis.parents("table").find('.chk-item').addClass('checked');
                    } else {
                        jqThis.parents("table").find('.chk-item').removeClass('checked');
                    }
                });
            }
        };
    })
    .directive('chkProductBox', ["$timeout", function ($timeout) {
        return {
            restrict: 'E',
            replace: true,
            template: '<div class="checkbox-group chk-item">' +
                '<div class="custom-checkbox bordered">' +
                '<i class="fa fa-check"></i>' +
                '</div>' +
                '</div>',
            link: function (scope, tElem, attr) {
                tElem.on('click', function () {
                    var that = this;
                    $timeout(function () {
                        var jqThis = $(that),
                            productName = jqThis.data("id");

                        jqThis.toggleClass('checked');

                        if (!jqThis.hasClass("checked")) {
                            // not check cu
                            scope.publishApp.clickProductToSetCuUnChecked(productName);

                        } else {
                            // checked cu ref
                            scope.publishApp.clickProductToSetCuChecked(productName);
                        }
                    });

                });
            }
        };
    }])
    .directive('productItem', ["$timeout", function ($timeout) {
        return {
            restrict: 'A',
            link: function (scope, tElem, attr) {
                tElem.on('click', function () {
                    var jqThis = $(this);
                    $timeout(function () {
                        jqThis.addClass("active").siblings().removeClass("active");

                        var productName = jqThis.find(".chk-item").data("id");
                        scope.publishApp.showCu(productName);
                    });
                });
            }
        };
    }])
    .directive('chkboxProductAll', ["$timeout", function ($timeout) {
        return {
            restrict: 'E',
            replace: true,
            template: '<div class="checkbox-group chk-all"><div class="custom-checkbox bordered"><i class="fa fa-check"></i></div></div>',
            link: function (scope, tElem, attr) {
                tElem.on('click', function () {

                    $timeout(function () {
                        scope.statusFlag.productCheckAll = !scope.statusFlag.productCheckAll;
                        scope.publishApp.getProductFilter();
                        // check all
                        if (scope.statusFlag.productCheckAll) {
                            scope.publishApp.chkAllProductData();

                        } else {
                            scope.publishApp.chkNoneProductData();
                        }
                    });

                });
            }
        };
    }])
    .directive('chkCuBox', ["$timeout", function ($timeout) {
        return {
            restrict: 'E',
            replace: true,
            template: '<div class="checkbox-group chk-item">' +
                '<div class="custom-checkbox bordered">' +
                '<i class="fa fa-check"></i>' +
                '</div>' +
                '</div>',
            link: function (scope, tElem, attr) {
                tElem.on('click', function () {
                    var jqThat = $(this);
                    $timeout(function () {
                        jqThat.toggleClass('checked');

                        var cuName = jqThat.next("span").text();
                        if (jqThat.hasClass("checked")) {
                            scope.publishApp.clickCuToSetCuChecked(cuName);
                        } else {
                            scope.publishApp.clickCuToSetCuUnChecked(cuName);
                        }
                    });
                });
            }
        };
    }])
    .directive('chkboxCuAll', ["$timeout", function ($timeout) {
        return {
            restrict: 'E',
            replace: true,
            template: '<div class="checkbox-group chk-all"><div class="custom-checkbox bordered"><i class="fa fa-check"></i></div></div>',
            link: function (scope, tElem, attr) {
                tElem.on('click', function () {
                    $timeout(function () {
                        scope.statusFlag.cuCheckAll = !scope.statusFlag.cuCheckAll;
                        scope.publishApp.getCuFilter();

                        // check all
                        var productName = $(".product .active").find(".chk-item").data("id");
                        if (scope.statusFlag.cuCheckAll) {
                            scope.publishApp.clickCuAllToSetCuChecked(productName);

                        } else {
                            // check nothing
                            scope.publishApp.clickCuAllToSetCuUnChecked(productName);
                        }
                    });
                });
            }
        };
    }])
    .directive('publishCuLastRepeat', function () {
        return {
            restrict: 'A',
            link: function (scope, tElem, attr) {
                if (scope.$last) {
                    scope.publishApp.setCheckAllStatus(scope.publishApp.jqCuRef);
                }
            }
        };
    })
    .directive('deleteProductLastRepeat', function () {
        return {
            restrict: 'A',
            link: function (scope, tElem, attr) {
                if (scope.$last) {
                    scope.publishApp.hideChkbox();
                }
            }
        };
    })
    .directive('addHost', function () {
        return {
            restrict: 'A',
            compile: function (tElem, attr) {
                tElem.attr('href', HOST + tElem.attr('href'));
            }
        };
    })
    .directive('alertModal', function () {
        return {
            restrict: 'A',
            replace: 'true',
            templateUrl: HOST + 'views/common/alert_modal.html'
        };
    })
    .directive('confirmModal', function () {
        return {
            restrict: 'A',
            replace: 'true',
            templateUrl: HOST + 'views/common/confirm_modal.html'
        };
    })
    .directive('uploadAppModal', function () {
        return {
            restrict: 'A',
            replace: 'true',
            templateUrl: HOST + 'views/appManage/upload_app_modal.html'
        };
    })
    .directive('upgradeRuleModal', function () {
        return {
            restrict: 'A',
            replace: 'true',
            templateUrl: HOST + 'views/appManage/upgrade_rule_modal.html'
        };
    })
    .directive('publishAppModal', function () {
        return {
            restrict: 'A',
            replace: 'true',
            templateUrl: HOST + 'views/appManage/publish_app_modal.html'
        };
    })
    .directive('publishedCuModal', function () {
        return {
            restrict: 'A',
            replace: 'true',
            templateUrl: HOST + 'views/appManage/published_cu_modal.html'
        };
    })
    /*todo show info*/
    .directive('appInfoModal', function () {
        return {
            restrict: 'A',
            replace: 'true',
            templateUrl: HOST + 'views/appManage/app_info_modal.html'
        };
    })

    // mouse over "upload-wrap" show x,
    // mouse out "upload-wrap" hide x
    .directive('uploadWrap', function () {
        return {
            restrict: 'A',
            link: function (scope, elem, attr) {
                elem.on('mouseover', function () {
                    var $uploadWrap = $(this);
                    $uploadWrap.each(function () {
                        var _$this = $(this);
                        var imgSrc = _$this.find('img').attr('src');
                        if (imgSrc) {
                            _$this.find('.icon-delete').show();
                        }
                    });
                }).on('mouseout', function () {
                    $(this).find('.icon-delete').hide();
                });
            }
        };
    })

    // get date time
    .directive('datetimepicker', function () {
        return {
            restrict: 'A',
            link: function (scope, elem, attr) {
                var datetimeParam = {
                    language: 'zh-CN',
                    format: 'yyyy-mm-dd',
                    showMeridian: true,
                    autoclose: 1,
                    startView: 2,
                    minView: 2,
                    todayBtn: true
                };

                elem.datetimepicker(datetimeParam);
            }
        };
    })

    // set init start time value base on end time
    .directive('setStartVal', function () {
        return {
            restrict: 'A',
            link: function (scope, elem, attr) {
                var datetimeParam = {
                    language: 'zh-CN',
                    format: 'yyyy-mm-dd',
                    showMeridian: true,
                    autoclose: 1,
                    startView: 2,
                    minView: 2,
                    todayBtn: true
                };

                //set rule
                var $endTime = $('#end-time');
                var $endTimeIpt = $endTime.find('input');

                $endTime.datetimepicker(datetimeParam).on('changeDate', function () {
                    elem.datetimepicker('setEndDate', $endTimeIpt.val());
                });

                $endTime.on('hide', function () {
                    elem.datetimepicker('setEndDate', $endTimeIpt.val());
                });
            }
        };
    })

    // set init end time value base on start time
    .directive('setEndVal', function () {
        return {
            restrict: 'A',
            link: function (scope, elem, attr) {
                var datetimeParam = {
                    language: 'zh-CN',
                    format: 'yyyy-mm-dd',
                    showMeridian: true,
                    autoclose: 1,
                    startView: 2,
                    minView: 2,
                    todayBtn: true
                };
                //set rule
                var $startTime = $('#start-time');
                var $startTimeIpt = $startTime.find('input');

                $startTime.datetimepicker(datetimeParam).on('changeDate', function () {
                    elem.datetimepicker('setStartDate', $startTimeIpt.val());
                });

                $startTime.on('hide', function () {
                    elem.datetimepicker('setStartDate', $startTimeIpt.val());
                });
            }
        };
    })

    // form validation
    .directive('appSequence', function () {
        return {
            require: "ngModel",
            link: function (scope, elem, attr, ngModel) {
                if (ngModel) {
                    var appSqcValidator = function (value) {
                        var validity = ngModel.$isEmpty(value) || ((+value || +value === 0) && value % 1 === 0 && value >= 0 && value <= 9999);
                        ngModel.$setValidity("appSequence", validity);
                        return validity ? value : undefined;
                    };
                    ngModel.$formatters.push(appSqcValidator);
                    ngModel.$parsers.push(appSqcValidator);
                }
            }
        };
    })
    .directive('appNumber', function () {
        return {
            require: "ngModel",
            link: function (scope, elem, attr, ngModel) {
                if (ngModel) {
                    var appNbrValidator = function (value) {
                        var validity = ngModel.$isEmpty(value) || (value > 0 && value % 1 === 0);
                        ngModel.$setValidity("appNumber", validity);
                        return validity ? value : undefined;
                    };
                    ngModel.$formatters.push(appNbrValidator);
                    ngModel.$parsers.push(appNbrValidator);
                }
            }
        };
    })
    .directive('percent', function () {
        return {
            require: "ngModel",
            link: function (scope, elem, attr, ngModel) {
                if (ngModel) {
                    var percentValidator = function (value) {
                        var validity = !ngModel.$isEmpty(value) && (value > 0 && value <= 100 && value % 1 === 0);
                        ngModel.$setValidity("percent", validity);
                        return validity ? value : undefined;
                    };
                    ngModel.$formatters.push(percentValidator);
                    ngModel.$parsers.push(percentValidator);
                }
            }
        };
    })
    .directive('timeValide', function () {
        return {
            require: "ngModel",
            link: function (scope, elem, attr, ngModel) {
                if (ngModel) {
                    var timeRegExp = /^[1-9][0-9][0-9][0-9]-[0-1]{0,1}[0-9]-[0-3]{0,1}[0-9]$/;
                    var timeValidator = function (value) {
                        var validity = ngModel.$isEmpty(value) || timeRegExp.test(value);
                        ngModel.$setValidity("timeValid", validity);
                        return validity ? value : undefined;
                    };
                    ngModel.$formatters.push(timeValidator);
                    ngModel.$parsers.push(timeValidator);
                }
            }
        };
    });